package com.kawins.util.web;

import com.alibaba.fastjson.JSON;
import com.kawins.result.ResultTo;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ajax工具类
 *
 * @author rankai
 *         createTime 2017-03-2017/3/6 16:33
 */
public class AjaxUtil {

    public static Boolean isAjax(HttpServletRequest request) {
        Boolean result = Boolean.TRUE;
         /*判断是否ajax请求*/
        if (!(request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            result = Boolean.FALSE;
        }
        return result;
    }

    /**
     * response方法
     *
     * @param response HttpServletResponse
     * @param resultTo ResultEnum
     */
    public static void outputMessage(HttpServletResponse response, ResultTo resultTo) {
        String json = JSON.toJSONString(resultTo);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            servletOutputStream.write(json.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (servletOutputStream != null) {
                try {
                    servletOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
